#include <func.h>

int main(int argc, char* argv[])
{
    // ARGS_CHECK(argc, 3);
    // int fdr = open(argv[1], O_RDONLY);
    // ERROR_CHECK(fdr, -1, "open");
    // int fdw = open(argv[2], O_WRONLY);
    // ERROR_CHECK(fdw, -1, "open");

    int fdr = open("1.pipe", O_RDONLY);
    ERROR_CHECK(fdr, -1, "open");
    int fdw = open("2.pipe", O_WRONLY);
    ERROR_CHECK(fdw, -1, "open");

    char buf[128] = {0};
    fd_set fd;
    int ret;
    while (1)
    {
        FD_ZERO(&fd);
        FD_SET(STDIN_FILENO, &fd);
        FD_SET(fdr, &fd);

        select(fdr + 1, &fd, NULL, NULL, NULL);

        if (FD_ISSET(STDIN_FILENO, &fd))
        {
            memset(buf, 0, sizeof(buf));
            ret = read(STDIN_FILENO, buf, sizeof(buf));
            // 我想结束聊天
            if (ret == 0)
            {
                // printf("I want to leave\n");
                break;
            }
            write(fdw, buf, strlen(buf) - 1);
        }
        if (FD_ISSET(fdr, &fd))
        {
            memset(buf, 0, sizeof(buf));
            ret = read(fdr, buf, sizeof(buf));
            // 对方想结束聊天
            if (ret == 0)
            {
                printf("the other side cancel this chat\n");
                break;
            }
            printf("get: %s\n", buf);
        }
    }
    close(fdr);
    close(fdw);
    return 0;
}